<template>
  <div class="power-statistics">
    <div class="chart-head clearfloat">
      <span class="tit theme-front-color">电量统计</span>
      <div class="search-d">
        <div class="tab-group small clearfloat">
          <span v-on:click="changeStatSearch(1)" v-bind:class="{active: statSearch == 1}">日</span>
          <span v-on:click="changeStatSearch(2)" v-bind:class="{active: statSearch == 2}">月</span>
        </div>
        <span class="search-input" v-show="statSearch == 1">
          <span class="theme-front-color">选择时间：</span>
          <el-date-picker
              type="date"
              size="small"
              v-model="statSearchDate"
              :picker-options="pickerOptions1"
              placeholder="选择日期"
              @change="changeData()"
            ></el-date-picker>
        </span>
        <span class="search-input" v-show="statSearch == 2">
          <span class="theme-front-color">选择时间：</span>
          <el-date-picker
              type="month"
              size="small"
              format="yyyy年MM月"
              v-model="statSearchMonth"
              :picker-options="pickerOptions1"
              placeholder="选择月份"
              @change="changeMonth()"
            ></el-date-picker>
        </span>
      </div>
    </div>
    <div class="statistics-d" v-show="statSearch == 1">
      <div id="statEchart1" v-show="dayEchartData.length > 0" :style="'height:'+(containerHeight/2-50)+'px'">
      </div>
      <div class="note" v-show="dayEchartData.length == 0">
        <img src="../../../assets/img/noechart.png" class="m-auto">
        <p>暂无相关数据</p>
      </div>
    </div>
    <div class="statistics-d" v-show="statSearch == 2">
      <div id="statEchart2" v-show="monthEchartData.length > 0" :style="'height:'+(containerHeight/2-50)+'px'" >
      </div>
      <div class="note" v-show="monthEchartData.length == 0">
        <img src="../../../assets/img/noechart.png"class="m-auto">
        <p>暂无相关数据</p>
      </div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import  commondef from '@/utils/common'
import * as Util from "@/utils";
export default {
  data() {
    return {
      meterCode:'',
      loadFlag:false,
      statSearch: 1,
      statSearchDate: new Date(new Date().getTime()),
      statSearchMonth: new Date(),
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      powerEchart: {
        option: {
          grid: {
            left: 40,
            top: 40,
            right: 20,
            bottom: 40
          },
          color: ['#708DE5', '#2BD597']
        },
        dateOption: {
          legend: {
            top: 10,
            right: 20,
            itemWidth: 10,
            itemHeight: 10,
            textStyle: {
              color: '#ffffff' // 设置图例文字颜色为白色
            },
            data: [{
              name:'上日',
              icon:'circle'
            }, {
              name:'当日',
              icon:'circle'
            }]
          },
          xAxis: {
            type: 'category',
            axisTick: { show: false },
            data: ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(val, n) {
              var returnStr = "<div style='text-align:left;'>" +
                "时间：" + val[0].name + ":00<br/>";
              for (var i in val) {
                returnStr = returnStr +
                  "<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:" + val[i].color + "'></span>" +
                  val[i].seriesName + "：" + parseInt(val[i].value) + " kWh" +
                  "<br/>"
              }
              returnStr = returnStr + "</div>";
              return returnStr;
            }
          }
        },
        monthOption: {
          legend: {
            top: 10,
            right: 20,
            itemWidth: 10,
            itemHeight: 10,
            textStyle: {
              color: '#ffffff' // 设置图例文字颜色为白色
            },
            data: [{
              name:'上月',
              icon:'circle'
            }, {
              name:'当月',
              icon:'circle'
            }]
          },
          xAxis: {
            type: 'category',
            data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(val, n) {
              var returnStr = "<div style='text-align:left;'>" +
                "时间：" + val[0].name + "日<br/>";
              for (var i in val) {
                returnStr = returnStr +
                  "<span style='display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:" + val[i].color + "'></span>" +
                  val[i].seriesName + "：" + val[i].value+ " kWh" +
                  "<br/>"
              }
              returnStr = returnStr + "</div>";
              return returnStr;
            }
          }
        }
      },
      dayEchartData: [],
      monthEchartData: []
    }
  },
  computed:{
    containerHeight() {
      return Util.getClientHeight() - 143;
    }
  },
  methods: {
    //刷新数据
    refreshData(data){
      this.meterCode =data
      if(this.statSearch == 1){
        this.changeData();
      }else{
        this.changeMonth();
      }
      //this.loadFlag = true;
    },
    changeStatSearch(status) {
      this.loadFlag = true;
      this.statSearch = status;
      //第一次切换的时候，获取月份的信息
      if(this.loadFlag && status == 2){
        this.changeMonth();
        this.loadFlag = false;
      }
    },
    changeData() {
      this.dayEchartData=[]
     // if(!this.$store.state.meterpara){
       // this.dayEchartData = [];
       // return false;
      //}
      var that = this;
      //获取年月
      var year = new Date(that.statSearchMonth).getFullYear();
      var premonth = new Date(that.statSearchMonth).getMonth();

      //请求
      var para = {
        meterCode: this.meterCode,
        customerId: this.$util.cookies.get("customer_id")
      }

      //获取日期时间
      var statSearchDate = that.statSearchDate.format('yyyy-MM-dd');
      var statSearchBeginDate = new Date(new Date(that.statSearchDate).getTime() - 24 * 60 * 60 * 1000).format('yyyy-MM-dd');

      para.begin = statSearchBeginDate;
      para.end = statSearchDate;

      this.$api.okhttp({
        url: this.$http.adornUrl('/eda/datavincent.reportservice.get_energydailyconsumbygroup'),
        method: 'post',
        data: this.$http.adornParams(para)
      }).then(res => {
        if (res.code === 0) {
          var data = res.data || [];
          if (data.length > 0 &&data[0].daily_data && data[0].daily_data.length > 0) {
            that.dayEchartData = data[0].daily_data || [];
            var options = {};
            //设置数组
             var data1=[];
             var data2 =[];
            if(data.length==1){
              if(data[0].date==statSearchDate){
                data2 =  data[0] ? data[0].consume_data : [];
              }
              else if(data[0].date==statSearchBeginDate){
                data1 = data[0] ? data[0].consume_data : [];
              }
            }else if(data.length==2){
              data1 = data[0] ? data[0].consume_data : [];
              data2 = data[1] ? data[1].consume_data : [];
            }

            options.series = [{
              name: '上日',
              type: 'bar',
              barGap: '20%',
              barCategoryGap: '40%',
              data: data1,
              itemStyle: {
                  //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                  emphasis: {
                      barBorderRadius: 30,
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(112,141,229, 0.5)'
                  },

                  normal: {
                      //柱形图圆角，初始化效果
                      barBorderRadius:10
                  }
              }
            }, {
              name: '当日',
              type: 'bar',
              barGap: '20%',
              barCategoryGap: '40%',
              data: data2,
              itemStyle: {
                  //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                  emphasis: {
                      barBorderRadius: 30,
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(3,213,151, 0.5)'
                  },

                  normal: {
                      //柱形图圆角，初始化效果
                      barBorderRadius:10
                  }
              }
            }];
            options.yAxis = {
              name: '单位 kWh',
              type: 'value',
              splitNumber: 5
            };
            //设置横坐标
            Object.assign(options, that.powerEchart.option, that.powerEchart.dateOption);

            //初始化图表
            setTimeout(function(){
              let myChart = echarts.init(document.getElementById('statEchart1'));
              myChart.clear();
              //画图
              myChart.setOption(options);
            }, 500);
          }
        }
      })
    },
    getLastDay (year, month) {
      let newYear = year  //  取当前的年份
      let newMonth = month  // 取下一个月的第一天，方便计算（最后一天不固定）
      let newDate = new Date(newYear, newMonth, 1)        //  取当年当月中的第一天
      return new Date(newDate.getTime() - 1000 * 60 * 60 * 24)
    },
    changeMonth() {
      this.monthEchartData=[]
      // if(!this.$store.state.meterpara){
      //   this.monthEchartData = [];
      //   return false;
      // }
      var that = this;
      //获取年月
      var year = this.statSearchMonth.getFullYear();
      var premonth = this.statSearchMonth.getMonth();

      //请求
     // var apiurl = api.urlList.datavincent.reportservice.get_multipled_energydailyconsumebygroup; //月份
      var para = {
        meterCode: this.meterCode,
        customerId: this.$util.cookies.get("customer_id")
      }
      //获取月份时间
      var statSearchMonth = that.statSearchMonth.format('yyyy-MM');
/*      var statSearchBeginMonth = year + "-" + (premonth > 9 ? premonth : "0" + premonth) + "-01";
      var statSearchEndMonth = year + "-" + (premonth + 2 > 9 ? premonth + 2 : "0" + (premonth + 2)) + "-01";
      if (premonth == 0) {
        statSearchBeginMonth = (year - 1) + "-12-01";
      }
      if (premonth == 12) {
        statSearchEndMonth = (year + 1) + "-01-31";
      }else{
        statSearchEndMonth = new Date(new Date(statSearchEndMonth).getTime() - 24 * 60 * 60 * 1000).format("yyyy-MM-dd")
      }*/
      let startmonth = this.statSearchMonth.getMonth()
      let startyear = this.statSearchMonth.getFullYear()
      if(startmonth===1){
        startyear = startyear-1
        startmonth= 12
      }else{
        startmonth=startmonth-1
      }

      var statSearchBeginMonth = new Date(startyear, startmonth, 1).format('yyyy-MM-dd')
      var statSearchEndMonth = that.getLastDay(this.statSearchMonth.getFullYear(), (this.statSearchMonth.getMonth() + 1)).format('yyyy-MM-dd')

      para.begin = statSearchBeginMonth;
      para.end = statSearchEndMonth;


      that.$http({
        url: that.$http.adornUrl('/eda/datavincent.reportservice.get_multipled_energydailyconsumebygroup'),
        method: 'post',
        data: this.$http.adornParams(para)
      }).then(res => {
        if(res.code === 0){
          var data = res.data;
          if (data) {
            //设置上月这月的数据
            var data1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];//上月
            var data2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];//本月
            //整理数据
            if(data.last&&data.last.length>0) {
              for (var i in  data.last) {
                var datei = data.last[i].date || '';
                var dayi = datei.substring(datei.length - 2);
                dayi = parseInt(dayi, 10) - 1;
                data1[dayi] = data.last[i].dailySum;
              }
            }
            if(data.cur&&data.cur.length>0) {
              for (var i in  data.cur) {
                var datei = data.cur[i].date || '';
                var dayi = datei.substring(datei.length - 2);
                dayi = parseInt(dayi, 10) - 1;
                data2[dayi] = data.cur[i].dailySum;
              }
            }
            var options = {};
            options.series = [{
              name: '上月',
              type: 'bar',
              barGap: '20%',
              barCategoryGap: '40%',
              data: data1,
              itemStyle: {
                //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                emphasis: {
                  barBorderRadius: 30,
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(112,141,229, 0.5)'
                },

                normal: {
                  //柱形图圆角，初始化效果
                  barBorderRadius: 10
                }
              }
              }, {
                  name: '当月',
                  type: 'bar',
                  barGap: '20%',
                  barCategoryGap: '40%',
                  data: data2,
                  itemStyle: {
                    //柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
                    emphasis: {
                      barBorderRadius: 30,
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(3,213,151, 0.5)'
                    },

                    normal: {
                      //柱形图圆角，初始化效果
                      barBorderRadius: 10
                    }
                  }
            }];
            var maxData = Math.max(...data2);
            var ktrue = false;
            if (maxData > 1000) {
              ktrue = true;
            }
            options.yAxis = {
              name: '单位 kWh',
              type: 'value',
              splitNumber: 5,
              axisLabel: {
                show: true,
                interval: 'auto',
                formatter: function (value, index) {
                  return ktrue ? Math.round(value / 10) * 0.01 + ' k' : value;
                }
              }
            };
            //获取横坐标长度
            var xAxis = that.powerEchart.monthOption.xAxis || {};
            var xAxisData = xAxis.data || [];
            //获取月份对应的日期
            var days1 = new Date(year, premonth, 0);
            if (premonth == 0) {
              days1 = new Date(year - 1, 12, 0);
            }
            days1 = days1.getDate();
            var days2 = new Date(year, premonth + 1, 0);
            days2 = days2.getDate();
            xAxisData = xAxisData.slice(0, days1 > days2 ? days1 : days2);
            // xAxisData = xAxisData.slice(0, data1.length > data2.length ? data1.length : data2.length);
            Object.assign(options, that.powerEchart.option, that.powerEchart.monthOption, {xAxis: [{data: xAxisData}]});
            //初始化图表
            this.monthEchartData = res.data.cur.concat(res.data.last);
            setTimeout(function () {
                let myChart = echarts.init(document.getElementById('statEchart2'));
                myChart.clear();
                //画图
                myChart.setOption(options);
            }, 300);
          }
        }
      });
    },
    queryParas() {
      var that = this;
      var para = {
        customer_id: that.$store.state.customer_id,
        enegcate_code: '023300',
        area_code: that.$store.state.customer_area_code.toString().substring(0, 2) + '0000',
        date: new Date().format('yyyy-MM-dd'),
        model: 'country'
      }
      return new Promise(function(resolve, reject) {
        api.axiosRequest(api.urlList.system.enegprice.query, para).then(res => {
          if (res.code === commondef.resCode.OK) {
            if (res.list &&
              res.list.length > 0 &&
              res.list[0].detail) {
              that.queryRow = res.list[0].detail.array
              resolve();
            } else {
              reject(res.error);
            }
          } else {
            that.$message.info(commondef.resMSG[res.code])
          }
        });
      });
    },
    monthApi(p) {
      var that = this;
      return new Promise(function(resolve, reject) {
        that.$http({
          url: that.$http.adornUrl('/eda/datavincent.reportservice.get_multipled_energydailyconsumebygroup'),
          method: 'post',
          data: this.$http.adornParams(p)
        }).then(res => {
          if (res.code === 0) {
            if (res.data !== null) {
              resolve(res.data)
            } else {
              that.$message.info('当月无数据，请选择其他月期查看')
              reject(res.error)
            }
          }
        })
      })
    },
  },
  watch: {
      // listenMeterpara: function(nvalue, pvalue) {
      //     console.log("修改前为：" + pvalue);
      //     console.log("修改后为：" + nvalue);
      //     if(nvalue){
      //       if(this.statSearch == 1){
      //         this.changeData();
      //       }else{
      //         this.changeMonth();
      //       }
      //       this.loadFlag = true;
      //
      //     }else{//清空
      //       this.dayEchartData = [];
      //       this.monthEchartData = [];
      //     }
      // }
  },
  mounted() {
   // this.changeData();
   // this.loadFlag = true;
  }
}

</script>
<style scoped lang="scss">
  @import "../../../assets/scss/_variables";



/*标题*/

.chart-head {
  margin-top: 10px;
}

.tit {
  float: left;
  font-size: 16px;
  line-height: 33px;
}

.search-d {
  float: right;
  font-size: 14px;
}

.search-d .tab-group {
  margin-top: 4px;
  float: left;
}

.search-input {
  margin-left: 20px;
}



/*tab*/

.tab-group.small {
  display: inline-block;
}

.tab-group span {
  color: #9c9c9c;
  display: inline-block;
  padding: 4px 30px;
  font-size: 14px;
  float: left;
  cursor: pointer;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  border-left: 1px solid #ccc;
}

.tab-group span.active {
  color: #fff;
  background-color: #708DE5;
  border-color: #708DE5;
  box-shadow: -1px 0 0 0 #708DE5;
}



/* .tab-group span:first-child {
  border-left: 1px solid #ccc;
} */

.tab-group span:last-child {
  border-right: 1px solid #ccc;
}

.tab-group span:first-child {
  border-radius: 5px 0 0 5px;
}

.tab-group span:last-child {
  border-radius: 0 5px 5px 0;
}

.tab-group.small span {
  padding: 2px 15px;
  font-size: 12px;
}




/*清除浮动代码*/

.clearfloat:after {
  display: block;
  clear: both;
  content: "";
  visibility: hidden;
  height: 0
}

.clearfloat {
  zoom: 1
}



/*提示*/

.note {
  padding: 20px;
  text-align: center;
  color: #666;
}

.note img {
  width: 140px;
}



/*页面*/

.power-statistics {
  padding: 5px 15px 10px;
  height: auto;
  /*background: $font-white;*/
}

.statistics-d>div {
  height: 250px;
}

</style>
